package com.rt.cloud.auth.config.response;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class ResponseSerializer extends StdSerializer<Response> {

    public ResponseSerializer() {
        super(Response.class);
    }



    @Override
    public void serialize(Response response, JsonGenerator gen, SerializerProvider provider) throws IOException {
        OAuth2AccessToken token = (OAuth2AccessToken) response.getObj();

        // short token
        String jti = (String) token.getAdditionalInformation().get("jti");

        gen.writeStartObject();
        Map<String, Object> map = new LinkedHashMap(token.getAdditionalInformation()); // user, authorities, jti
        // map.put("access_token", token.getValue());
        map.put("access_token", jti);

        if (token.getRefreshToken() != null) {
            map.put("refresh_token", token.getRefreshToken().getValue());
        }

        gen.writeNumberField("code", 0);
        gen.writeBooleanField("success", true);
        gen.writeStringField("contentOnly", response.getContentOnly());
        gen.writeStringField("content", response.getContent());
        gen.writeObjectField("map",map);


        gen.writeEndObject();
    }

}
